//
//  ZhuangCheMainVC.m
//  LogisticsSupplier
//
//  Created by 吕晶 on 2021/4/12.
//  Copyright © 2021 吕晶. All rights reserved.
//

#import "ZhuangCheMainVC.h"
#import "ZhuangCheMainModel.h"
#import "ZhuangCheMainHeadView.h"
#import "ZhuangCheMainGoodCell.h"
#import "ShouDongDianHuoVC.h"
#import "ZhuangCheNoticeAlertView.h"
#import "ZhuangCheMainNavBar.h"
#import "AbnormalReportMainVC.h"

@interface ZhuangCheMainVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) ZhuangCheMainNavBar *navBar;
@property (nonatomic, strong) ZhuangCheMainHeadView *topView;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) ZhuangCheMainModel *model;

@end

@implementation ZhuangCheMainVC

-(ZhuangCheMainModel *)model {
    if (!_model) {
        _model = [ZhuangCheMainModel new];
    }
    return _model;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.topView.nim_bottom, ScreenW, ScreenH - self.navBar.nim_height - self.topView.nim_height - self.bottomView.nim_height) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = Color_backgroundColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

-(ZhuangCheMainNavBar *)navBar {
    if (!_navBar) {
        _navBar = [[ZhuangCheMainNavBar alloc] initWithFrame:CGRectMake(0, 0, ScreenW, NaviHeight)];
        _navBar.titleStr = @"点货装车";
        __weak_self;
        _navBar.backBlock = ^{
            [weakself.rt_navigationController popViewControllerAnimated:YES];
        };
        _navBar.yiChangBlock = ^{
            AbnormalReportMainVC *vc = [AbnormalReportMainVC new];
            vc.isPush = YES;
            vc.sta_id = weakself.sta_id;
            vc.dp_id = weakself.dp_id;
            vc.type = 2;
            [weakself.rt_navigationController pushViewController:vc animated:YES];
        };
        _navBar.yiJianBlock = ^{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确认一键装车？" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [weakself requestForYiJianZhuangChe:weakself.dp_id];
            }];
            UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alert addAction:sureAction];
            [alert addAction:cancleAction];
            [weakself presentViewController:alert animated:YES completion:nil];
        };
    }
    return _navBar;
}

- (void)requestForYiJianZhuangChe:(NSString *)dp_id {
    [HttpRequest PostWithApi:LogisticsSupplierTaskZhuangChe params:@{@"sta_id":self.sta_id,@"type":@(2),@"dp_id":dp_id} progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshTaskManagerDetail object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshTaskManagerList object:nil];
            __weak_self;
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"装车成功" delayOperation:^{
                [weakself.rt_navigationController popViewControllerAnimated:YES];
            }];
        }
    } fail:^(NSError * _Nonnull error) {

    }];
}

-(ZhuangCheMainHeadView *)topView {
    if (!_topView) {
        _topView = [ZhuangCheMainHeadView new];
        _topView.model = self.model;
        _topView.frame = CGRectMake(0, self.navBar.nim_bottom, ScreenW, self.topView.height);
    }
    return _topView;
}

-(UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenH - 64 - BottomHeight, ScreenW, 64 + BottomHeight)];
        _bottomView.backgroundColor = HexColor(0xffffff);
        
        CGFloat btnW = (ScreenW - 20 - 20 - 25 - 10) * 0.33333;
        CGFloat btnH = 44;
//        UIButton *scanBtn = [[UIButton alloc] initWithFrame:CGRectMake(20, 10, btnW, btnH)];
//        [scanBtn setTitle:@"扫码点货" forState:0];
//        [scanBtn setTitleColor:Color_ThemeColor forState:0];
//        scanBtn.titleLabel.font = BoldFontOfSize(16);
//        scanBtn.backgroundColor = HexColorA(0x3D68EB, 0.1);
//        scanBtn.layer.masksToBounds = YES;
//        scanBtn.layer.cornerRadius = 6;
//        [scanBtn addTarget:self action:@selector(scanClick) forControlEvents:UIControlEventTouchUpInside];
//        [_bottomView addSubview:scanBtn];
//        scanBtn.hidden = YES;
        
        UIButton *shouDongBtn = [[UIButton alloc] initWithFrame:CGRectMake(20, 10, ScreenW - 20 - btnW - 25 - 20, btnH)];
        [shouDongBtn setTitle:@"手动点货" forState:0];
        [shouDongBtn setTitleColor:Color_ThemeColor forState:0];
        shouDongBtn.titleLabel.font = BoldFontOfSize(16);
        shouDongBtn.backgroundColor = HexColorA(0x3D68EB, 0.1);
        shouDongBtn.layer.masksToBounds = YES;
        shouDongBtn.layer.cornerRadius = 6;
        [shouDongBtn addTarget:self action:@selector(shouDongClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:shouDongBtn];
        
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(25 + shouDongBtn.nim_right, 10, btnW, btnH)];
        [btn setTitleColor:HexColor(0xffffff) forState:0];
        btn.titleLabel.font = BoldFontOfSize(16);
        btn.backgroundColor = Color_ThemeColor;
        btn.layer.masksToBounds = YES;
        btn.layer.cornerRadius = 6;
        [btn setTitle:@"提交" forState:0];
        [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:btn];
    }
    return _bottomView;
}

//扫码点货
- (void)scanClick {
    
}

//手动点货
- (void)shouDongClick {
    ShouDongDianHuoVC *vc = [ShouDongDianHuoVC new];
    vc.mainModel = self.model;
    __weak_self;
    vc.finishBlock = ^{
        [weakself.tableView reloadData];
    };
    [self.rt_navigationController pushViewController:vc animated:YES];
}

//提交
- (void)btnClick {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确认提交？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self requestForCommit];
    }];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:sureAction];
    [alert addAction:cancleAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)requestForCommit {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:self.sta_id forKey:@"sta_id"];
    [dic setObject:self.dp_id forKey:@"dp_id"];
    NSMutableArray *goodArr = [NSMutableArray array];
    __block BOOL hasYiChang = NO;
    [self.model.goods_list enumerateObjectsUsingBlock:^(ZhuangCheMainGoodModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *dd = [NSMutableDictionary dictionary];
        [dd setObject:@(obj.g_id) forKey:@"g_id"];
        [dd setObject:@(obj.z_count) forKey:@"num"];
        [dd setObject:@(obj.z_piece) forKey:@"pnum"];
        [goodArr addObject:dd];
        if ((obj.z_count != obj.num) || (obj.z_piece != obj.pnum)) {
            hasYiChang = YES;
        }
    }];
    if (goodArr.count) {
        [dic setObject:[FactoryMethod stringWithJSONData:goodArr] forKey:@"goods"];
    }
    if (hasYiChang) {
        [dic setObject:@(1) forKey:@"type"];
        ZhuangCheNoticeAlertView *alert = [ZhuangCheNoticeAlertView new];
        __weak_self;
        alert.sureBlock = ^{
            [weakself requestForZhuangChe:dic];
        };
        [alert showInView:MAIN_WINDOW];
    }else {
        [dic setObject:@(2) forKey:@"type"];
        [self requestForZhuangChe:dic];
    }
}

- (void)requestForZhuangChe:(NSMutableDictionary *)dic {
    [HttpRequest PostWithApi:LogisticsSupplierTaskZhuangChe params:dic progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshTaskManagerDetail object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshTaskManagerList object:nil];
            __weak_self;
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"提交成功" delayOperation:^{
                [weakself.rt_navigationController popViewControllerAnimated:YES];
            }];
        }
    } fail:^(NSError * _Nonnull error) {

    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"点货装车";
    self.navigationController.navigationBar.hidden = YES;
    [self.view addSubview:self.navBar];
    [self.view addSubview:self.topView];
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.tableView];
    [self requestForData];
}

- (void)requestForData {
    [HttpRequest PostWithApi:LogisticsSupplierTaskZhuangCheInfo params:@{@"sta_id":self.sta_id,@"dp_id":self.dp_id} progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.model = [ZhuangCheMainModel mj_objectWithKeyValues:responseObject];
            self.topView.model = self.model;
            [self configUI];
            [self.tableView reloadData];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)configUI {
    self.topView.nim_height = self.topView.height;
    self.tableView.frame = CGRectMake(0, self.topView.nim_bottom, ScreenW, ScreenH - NaviHeight - self.topView.nim_height - self.bottomView.nim_height);
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.model.goods_list.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZhuangCheMainGoodCell *cell = [ZhuangCheMainGoodCell ZhuangCheMainGoodCellWithTableView:tableView];
    ZhuangCheMainGoodModel *model = self.model.goods_list[indexPath.section];
    cell.goodModel = model;
    cell.clickBlock = ^{
        model.isOpen = !model.isOpen;
        [tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZhuangCheMainGoodCell *cell = [ZhuangCheMainGoodCell ZhuangCheMainGoodCellWithTableView:tableView];
    ZhuangCheMainGoodModel *model = self.model.goods_list[indexPath.section];
    cell.goodModel = model;
    return cell.height;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ShouDongDianHuoVC *vc = [ShouDongDianHuoVC new];
    vc.mainModel = self.model;
    vc.clickModel = self.model.goods_list[indexPath.section];
    __weak_self;
    vc.finishBlock = ^{
        [weakself.tableView reloadData];
    };
    [self.rt_navigationController pushViewController:vc animated:YES];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
    view.backgroundColor = Color_backgroundColor;
    if (section == 0) {
        return view;
    }
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 10;
    }
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
    view.backgroundColor = Color_backgroundColor;
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

@end
